from datetime import datetime
import pyqt5_tools
import PyQt5
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QPropertyAnimation, QPoint, QEasingCurve
from PyQt5.QtGui import QIcon, QFont, QPalette, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget, QLabel, QLineEdit, QPushButton, QListWidget, \
    QMessageBox, QComboBox, QStyleFactory

import webbrowser  # 导入 webbrowser 库
import main
import minecraft_launcher_lib
import os
import logging
import json  # 导入 json 模块

# 配置文件路径
CONFIG_FILE = "config.json"  # 配置文件的路径

def save_config(config_data):
    """
    将配置数据保存到文件

    参数:
    config_data (dict): 要保存的配置数据
    """
    with open(CONFIG_FILE, 'w') as file:
        json.dump(config_data, file)

def load_config():
    """
    加载配置文件，如果文件不存在则创建默认配置

    返回:
    dict: 加载的配置数据
    """
    if not os.path.exists(CONFIG_FILE):
        # 如果文件不存在，创建一个并保存默认配置
        default_config = {
            "minecraft_dir": ".minecraft",
            "minecraft_JVM": "2048m",
            "launcher_name": "MinecraftpyFPL",
            "launcher_version": "0.0.1",
            "resolution": "1920x1080"  # 默认分辨率
        }
        save_config(default_config)
    with open(CONFIG_FILE, 'r') as file:
        return json.load(file)

class VersionDataThread(QThread):
    """
    用于获取版本数据的线程
    """
    versionDataReady = pyqtSignal(list)

    def run(self):
        """
        线程执行的操作，获取版本列表数据
        """
        try:
            versions = minecraft_launcher_lib.utils.get_version_list()
            self.versionDataReady.emit(versions)
        except Exception as e:
            logging.error(f"哎呀，获取版本数据时出了点岔子: {e}")

class Ui_launcher(QWidget):
    """
    主窗口类
    """
    def __init__(self):
        """
        构造函数，初始化窗口
        """
        super().__init__()

        # 加载配置
        self.config = load_config()

        self.setAutoFillBackground(True)
        palette = self.palette()
        # 使用相对路径设置背景图片
        palette.setBrush(QPalette.Background, QPixmap(os.path.join(current_dir, 'img/background.jpg')))
        self.setPalette(palette)

        # 加载 CSS 样式表
        self.loadStylesheet('styles.css')  # 这里指定 CSS 文件路径

        # 窗口淡入动画
        self.animation = QPropertyAnimation(self, b"windowOpacity")
        self.animation.setDuration(500)  # 动画持续时间 500 毫秒
        self.animation.setStartValue(0)  # 起始透明度为 0（完全透明）
        self.animation.setEndValue(1)  # 结束透明度为 1（完全不透明）
        self.animation.start()

        self.initUI()

    def loadStylesheet(self, filename):
        """
        加载 CSS 样式表

        参数:
        filename (str): 样式表文件的路径
        """
        with open(filename, 'r') as file:
            self.setStyleSheet(file.read())

    def initUI(self):
        """
        初始化窗口界面元素
        """
        # 窗口
        self.setGeometry(0, 0, 600, 400)
        self.setWindowTitle("MinecraftpyFPL")
        # 使用相对路径设置窗口图标
        self.setWindowIcon(QIcon(os.path.join(current_dir, 'img/icon.png')))

        # 居中
        self.center()

        # 文本 启动器标题
        self.title = QLabel(self)
        self.title.setGeometry(20, 0, 300, 60)
        self.title.setText("MinecraftpyFPL")
        self.title.setVisible(True)
        self.title.setFont(QFont("等线 Light", 20, QFont.Light))
        self.title.setStyleSheet("color: black")  # 更改颜色

        # 玩家名上方显示史蒂夫头像
        self.steve_icon = QLabel(self)
        self.steve_icon.setGeometry(50, 100, 50, 50)
        self.steve_icon.setPixmap(QPixmap(os.path.join(current_dir, 'img/steve.png')))  # 假设史蒂夫图片名为 steve.png

        # 文本 “玩家名：”
        self.Player_name_label = QLabel(self)
        self.Player_name_label.setGeometry(50, 155, 50, 20)
        self.Player_name_label.setText("玩家名：")
        self.Player_name_label.setVisible(True)

        # 输入玩家名
        self.Player_name = QLineEdit(self)
        self.Player_name.setGeometry(50, 180, 230, 30)
        self.Player_name.setFont(QFont("等线 Light", 10))
        self.Player_name.setVisible(True)

        # MC启动！

        self.StartGameButton = QPushButton(self)
        self.StartGameButton.setText("启动游戏")
        self.StartGameButton.setFont(QFont("等线 Light", 20, QFont.Bold))
        self.StartGameButton.setVisible(True)
        self.StartGameButton.setGeometry(50, 230, 230, 60)
        self.StartGameButton.clicked.connect(self.StartGameButtonClicked)

        # 已安装的版本列表按钮
        self.InstalledListButton = QPushButton(self)
        self.InstalledListButton.setText("版本列表")
        self.InstalledListButton.setGeometry(50, 295, 230, 30)
        self.InstalledListButton.setVisible(True)
        self.InstalledListButton.clicked.connect(self.InstalledVersionListButtonClicked)

        # 已安装的版本列表
        self.VersionsList = QListWidget(self)
        self.VersionsList.setGeometry(340, 40, 250, 340)
        self.VersionsList.setVisible(True)

        # 版本下载按钮
        self.DownloadButton = QPushButton(self)
        self.DownloadButton.setText("版本下载")
        self.DownloadButton.setGeometry(50, 330, 230, 30)
        self.DownloadButton.setVisible(True)
        self.DownloadButton.clicked.connect(self.DownloadVersionsButtonClicked)

        # 下载按钮
        self.DownloadVersionButton = QPushButton(self)
        self.DownloadVersionButton.setText("下载该版本")
        self.DownloadVersionButton.setGeometry(340, 10, 250, 30)
        self.DownloadVersionButton.clicked.connect(self.DownloadButtonClicked)

        # 版本设置
        self.SettingButton = QPushButton(self)
        self.SettingButton.setText("版本设置")
        self.SettingButton.setGeometry(50, 375, 230, 30)
        self.SettingButton.setVisible(True)
        self.SettingButton.clicked.connect(self.SettingButtonClicked)

        # 打开网页按钮
        self.OpenWebButton = QPushButton(self)
        self.OpenWebButton.setText("关于我们")
        self.OpenWebButton.setGeometry(50, 410, 230, 30)
        self.OpenWebButton.clicked.connect(self.openWeb)  # 连接到打开网页的函数

        # 版本设置页：

        # 返回按钮
        self.BackButton = QPushButton(self)
        self.BackButton.setText("返回")
        self.BackButton.setGeometry(520, 10, 80, 30)
        self.BackButton.clicked.connect(self.BackButtonClick)

        # 文本 设置
        self.SettingLabel = QLabel(self)
        self.SettingLabel.setText("设置")
        self.SettingLabel.setFont(QFont("等线 Light", 28, QFont.Light))
        self.SettingLabel.setGeometry(0, 0, 100, 50)

        # 文本 Java选择
        self.JavaLabel = QLabel(self)
        self.JavaLabel.setText("选择java")
        self.JavaLabel.setGeometry(20, 50, 100, 30)

        # Java下拉列表
        self.JavaList = QComboBox(self)
        self.findJava()
        self.JavaList.setGeometry(20, 75, 260, 20)

        # Java按钮
        self.JavaButton = QPushButton(self)
        self.JavaButton.setText("确定")
        self.JavaButton.setGeometry(210, 100, 70, 20)
        self.JavaButton.clicked.connect(self.JavaButtonClick)

        # 分辨率选择下拉列表
        self.ResolutionComboBox = QComboBox(self)
        self.ResolutionComboBox.addItems(["1920x1080", "1280x720", "1024x768","2560×1440","3840×2160","1366×768","1280×720","1280×800","- 2732×2048"])  # 示例分辨率
        self.ResolutionComboBox.setGeometry(20, 130, 260, 20)
        self.ResolutionComboBox.currentIndexChanged.connect(self.changeResolution)

        # 启动版本数据获取线程
        self.versionThread = VersionDataThread()
        self.versionThread.versionDataReady.connect(self.updateVersionsList)
        self.versionThread.start()

    def updateVersionsList(self, versions):
        """
        更新版本列表

        参数:
        versions (list): 新版本列表数据
        """
        self.VersionsList.clear()
        for version in versions:
            self.VersionsList.addItem(version["id"])
        print("嘿，版本列表更新啦，快来瞅瞅！")

    def center(self):
        """
        使窗口居中显示
        """
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def StartGameButtonClicked(self):
        """
        启动游戏按钮点击事件处理
        """
        # 按钮点击缩放动画
        animation = QPropertyAnimation(self.StartGameButton, b"geometry")
        animation.setDuration(100)  # 动画持续时间 100 毫秒
        start_geometry = self.StartGameButton.geometry()
        end_geometry = QRect(start_geometry.x() - 5, start_geometry.y() - 5, start_geometry.width() + 10, start_geometry.height() + 10)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        try:
            self.DownloadVersionButton.setVisible(False)
            minecraft_version = self.VersionsList.selectedItems()[0].text()
            logging.info(f"Selected Minecraft version: {minecraft_version}")
            if not self.Player_name.text():
                raise ValueError("Player name is empty.")
            if not minecraft_version:
                raise ValueError("Minecraft version is not selected")
            if not minecraft_JavaPath:
                raise ValueError("Java path is not selected.")
            main.GameStart(str(self.Player_name.text()), minecraft_dir, minecraft_version, minecraft_JVM, minecraft_JavaPath)
            self.VersionsList.clear()
        except Exception as e:
            logging.error(f"哎呀，启动游戏时遇到麻烦啦: {e}")
            QMessageBox.warning(self, '警告', "您可能遇到了一些问题，请把打包好的日志文件发送给我们，在这之前，您可以尝试重新启动", QMessageBox.Ok)

    def InstalledVersionListButtonClicked(self):
        """
        已安装版本列表按钮点击事件处理
        """
        # 按钮点击动画
        animation = QPropertyAnimation(self.InstalledListButton, b"geometry")
        animation.setDuration(100)
        start_geometry = self.InstalledListButton.geometry()
        end_geometry = QRect(start_geometry.x() + 5, start_geometry.y() + 5, start_geometry.width() - 10, start_geometry.height() - 10)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        self.DownloadVersionButton.setVisible(False)
        self.VersionsList.clear()
        try:
            minecraft_versions = minecraft_launcher_lib.utils.get_installed_versions(minecraft_directory=minecraft_dir)
            for version in minecraft_versions:
                self.VersionsList.addItem(version["id"])
        except Exception as e:
            logging.error(f"哎呀，获取已安装版本列表时出错啦: {e}")

    def DownloadVersionsButtonClicked(self):
        """
        版本下载按钮点击事件处理
        """
        # 按钮点击动画
        animation = QPropertyAnimation(self.DownloadVersionsButton, b"geometry")
        animation.setDuration(100)
        start_geometry = self.DownloadVersionsButton.geometry()
        end_geometry = QRect(start_geometry.x() - 5, start_geometry.y() - 5, start_geometry.width() + 10, start_geometry.height() + 10)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        self.DownloadVersionButton.setVisible(True)
        self.VersionsList.clear()

    def DownloadButtonClicked(self):
        """
        下载按钮点击事件处理
        """
        # 按钮点击动画
        animation = QPropertyAnimation(self.DownloadButton, b"geometry")
        animation.setDuration(100)
        start_geometry = self.DownloadButton.geometry()
        end_geometry = QRect(start_geometry.x() + 5, start_geometry.y() + 5, start_geometry.width() - 10, start_geometry.height() - 10)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        try:
            DownloadVersion = self.VersionsList.selectedItems()[0].text()
            minecraft_launcher_lib.install.install_minecraft_version(DownloadVersion, minecraft_dir)
        except Exception as e:
            logging.error(f"哎呀，下载版本时遇到状况了: {e}")
            QMessageBox.warning(self, '警告', "您可能遇到了一些问题，在这之前，您可以尝试重新启动", QMessageBox.Ok)

    def findJava(self):
        """
        查找 Java 版本
        """
        try:
            Java = minecraft_launcher_lib.java_utils.find_system_java_versions()
            for java_version in Java:
                self.JavaList.addItem(java_version)
        except Exception as e:
            logging.error(f"哎呀，找 Java 版本时碰到难题啦: {e}")

    def SettingButtonClicked(self):
        """
        版本设置按钮点击事件处理
        """
        # 隐藏动画
        animation = QPropertyAnimation(self.SettingButton, b"geometry")
        animation.setDuration(300)
        animation.setEasingCurve(QEasingCurve.OutBack)  # 使用弹性效果
        start_geometry = self.SettingButton.geometry()
        end_geometry = QRect(-100, start_geometry.y(), 0, start_geometry.height())
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        # 其他元素的隐藏
        self.DownloadVersionButton.setVisible(False)
        self.title.setVisible(False)
        self.DownloadButton.setVisible(False)
        self.VersionsList.setVisible(False)
        self.Player_name.setVisible(False)
        self.InstalledListButton.setVisible(False)
        self.StartGameButton.setVisible(False)
        self.Player_name_label.setVisible(False)
        self.OpenWebButton.setVisible(False)  # 隐藏打开网页按钮

        # 显示相关元素
        self.BackButton.setVisible(True)
        self.JavaLabel.setVisible(True)
        self.SettingLabel.setVisible(True)
        self.JavaList.setVisible(True)
        self.JavaButton.setVisible(True)
        self.ResolutionComboBox.setVisible(True)  # 显示分辨率选择下拉列表

    def BackButtonClick(self):
        """
        返回按钮点击事件处理
        """
        # 显示动画
        animation = QPropertyAnimation(self.SettingButton, b"geometry")
        animation.setDuration(300)
        animation.setEasingCurve(QEasingCurve.OutBack)  # 使用弹性效果
        start_geometry = self.SettingButton.geometry()
        end_geometry = QRect(50, 375, 230, 30)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        self.SettingButton.setVisible
    def BackButtonClick(self):
        """
        返回按钮点击事件处理
        """
        # 显示动画
        animation = QPropertyAnimation(self.SettingButton, b"geometry")
        animation.setDuration(300)
        animation.setEasingCurve(QEasingCurve.OutBack)  # 使用弹性效果
        start_geometry = self.SettingButton.geometry()
        end_geometry = QRect(50, 375, 230, 30)
        animation.setStartValue(start_geometry)
        animation.setEndValue(end_geometry)
        animation.start()

        self.SettingButton.setVisible(True)
        self.title.setVisible(True)
        self.DownloadButton.setVisible(True)
        self.VersionsList.setVisible(True)
        self.Player_name.setVisible(True)
        self.InstalledListButton.setVisible(True)
        self.StartGameButton.setVisible(True)
        self.Player_name_label.setVisible(True)
        self.OpenWebButton.setVisible(True)  # 显示打开网页按钮

        self.BackButton.setVisible(False)
        self.JavaLabel.setVisible(False)
        self.SettingLabel.setVisible(False)
        self.JavaList.setVisible(False)
        self.JavaButton.setVisible(False)
        self.ResolutionComboBox.setVisible(False)  # 隐藏分辨率选择下拉列表

    def JavaButtonClick(self):
        """
        Java 选择确定按钮点击事件处理
        """
        global minecraft_JavaPath
        minecraft_JavaPath = self.JavaList.currentText()
        QMessageBox.information(self, '信息', "Java 选择成功！", QMessageBox.Ok)

    def changeResolution(self):
        """
        分辨率选择下拉列表变化事件处理
        """
        selected_resolution = self.ResolutionComboBox.currentText()
        print(f"您选择了 {selected_resolution} 分辨率，希望这个选择能让您看得更清楚！")

    def openWeb(self):  # 打开网页的函数
        """
        打开网页按钮点击事件处理
        """
        webbrowser.open('https://scicat3671745081.github.io/')
        print("嘿，网页打开啦，祝您玩得开心！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create('Fusion'))  # 设置为 Fusion 风格，使界面更美观
    Ui = Ui_launcher()
    Ui.show()
    sys.exit(app.exec_())
